package controllers;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import models.EnvioPromo;
import models.EstablecimientoAlimenticio;
import models.Perfil;
import models.Promo;
import notifiers.Notificador;
import play.data.binding.Binder;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.With;
import controllers.securesocial.SecureSocial;

@With(SecureSocial.class)
public class Promos extends CustomCRUD {
    
	protected static String getControllerName() {
		
		ObjectType type = ObjectType.get(getControllerClass());
		
		return type.name;
	}
	
	public static void list(int page, String search, String searchFields, String orderBy, String order) {
		
		ObjectType type = ObjectType.get(getControllerClass());
		notFoundIfNull(type);
		
		if (page < 1) {
			page = 1;
		}
		
		List<Promo> objects = ((EstablecimientoAlimenticio)getUsuarioLogueado()).getPromos();
		
		Long count = new Long(objects.size());
		Long totalCount = new Long(objects.size());
		
        try {
            render(type, objects, count, totalCount, page, orderBy, order);
        } catch (TemplateNotFoundException e) {
            render(getControllerName() + "/list.html", type, objects, count, totalCount, page, orderBy, order);
        }
	}
	
	public static void enviarPromo(String promoId) throws Exception {
		
		ObjectType type = ObjectType.get(getControllerClass());
		notFoundIfNull(type);
		
		Promo promo = (Promo)type.findById(promoId);
		notFoundIfNull(promo);
		
		List<Perfil> destinatarios = (Perfil.find("byRecibePromos", Boolean.TRUE).fetch());
		
		Notificador.emailPromocion(promo, destinatarios);
		
		EnvioPromo envioPromo = new EnvioPromo(Calendar.getInstance().getTime(), new Integer(destinatarios != null ? destinatarios.size() : 0));
		
		promo.getEnvioPromos().add(envioPromo);
		promo.save();
		
		Promos.list(0, null, null, null, null);
	}
	
	public static List<List<Integer>> cargarGrafico(Long promoId, Date fechaInicio, Date fechaFin) throws Exception {
		
		ObjectType type = ObjectType.get(getControllerClass());
		notFoundIfNull(type);
		
		Promo promo = (Promo) type.findById(promoId.toString());
		
		notFoundIfNull(promo);
		
		if (fechaInicio == null) {
			Calendar fecha = Calendar.getInstance();
			fecha.add(Calendar.MONTH, -1);
			fechaInicio = fecha.getTime();
		}
		
		fechaFin = (fechaFin == null) ? Calendar.getInstance().getTime() : fechaFin;
		
		Integer datoIndex = 0;
		
		List<List<Integer>> fechasDeEnvios = new ArrayList<List<Integer>>();
		
		// arma un array asi [1,45],[2,46],[3,46],[4,47],
		for (EnvioPromo envioPromo : promo.getEnvioPromos()) {
			
			datoIndex++;
			
			if (envioPromo.getFechaEnviado().before(fechaFin) && envioPromo.getFechaEnviado().after(fechaInicio)) {
				
				List<Integer> envio = new ArrayList<Integer>();
				
				envio.add(datoIndex);
				envio.add(envioPromo.getCantidadEnviada());
				
				fechasDeEnvios.add(envio);
			}
		}
		
		return fechasDeEnvios;
	}
	
    public static void save(String id) throws Exception {
        
    	ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        
        Model object = type.findById(id);
        notFoundIfNull(object);
        
        Binder.bindBean(params.getRootParamNode(), "object", object);
        
        ((Promo)object).setEstablecimientoAlimenticio((EstablecimientoAlimenticio)getUsuarioLogueado());
        
        validation.valid(object);
        
        if (validation.hasErrors()) {
            
        	renderArgs.put("error", play.i18n.Messages.get("crud.hasErrors"));
            
        	try {
                render(request.controller.replace(".", "/") + "/show.html", type, object);
            } catch (TemplateNotFoundException e) {
                render(getControllerName() + "/show.html", type, object);
            }
        }
        
        object._save();
        
        flash.success(play.i18n.Messages.get("crud.saved", type.modelName));
        
        if (params.get("_save") != null) {
            redirect(request.controller + ".list");
        }
        
        redirect(request.controller + ".show", object._key());
    }
    
    public static void create() throws Exception {
    	
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        
        Constructor<?> constructor = type.entityClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        
        Model object = (Model) constructor.newInstance();
        
        Binder.bindBean(params.getRootParamNode(), "object", object);
        
        ((Promo)object).setEstablecimientoAlimenticio((EstablecimientoAlimenticio)getUsuarioLogueado());
        
        validation.valid(object);
        
        if (validation.hasErrors()) {
            renderArgs.put("error", play.i18n.Messages.get("crud.hasErrors"));
            try {
                render(request.controller.replace(".", "/") + "/blank.html", type, object);
            } catch (TemplateNotFoundException e) {
                render("CRUD/blank.html", type, object);
            }
        }
        
        object._save();
        
        flash.success(play.i18n.Messages.get("crud.created", type.modelName));
        
        if (params.get("_save") != null) {
            redirect(request.controller + ".list");
        }
        if (params.get("_saveAndAddAnother") != null) {
            redirect(request.controller + ".blank");
        }
        redirect(request.controller + ".show", object._key());
    }
    
}
